//
//  StaffManagerViewController.m
//  QRMaster
//
//  Created by myApple on 15/4/13.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "StaffManagerViewController.h"
#import "LineView.h"
#import "RoomSeclectViewController.h"
#import "AccessSeclectViewController.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "StaffInfoView.h"
#import "Reachability.h"
#import "StaffTimeSelectViewController.h"
#import "StaffInfoCell.h"
#import "UIImageView+WebCache.h"
#import "JudgeRole.h"
#import "DeleteView.h"
#import "StaffLogic.h"
#import "BackBtn.h"
#import "EidtStaffInfoController.h"
#import "InternationalControl.h"
#import "EditStaffRoleController.h"

@interface StaffManagerViewController ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,UIActionSheetDelegate>
{
    UILabel * nameLabel;
    UILabel * telePhoneLabel;
    NSArray * roleArray;//管理角色
    NSInteger rolePower;//操作人和被操作人的角色关系(0 是普通职员或者权限相等，1 超级管理员，2 管理员对普通职员的操作)
    UITableView * staffInfoTabelView;
    NSArray * titleNameArray;
    UILabel * staffNameLabel;
    UIImageView * sexImageView;
    UIView * firstSectionView;
    UIButton * moreViewBtn;//右上角的button
    UIView * backView;//透明的遮罩层
    UIView * backListView;//下拉黑色view
    UIButton * backBtn;//返回键
    
}

@end

@implementation StaffManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"detailInfo", nil);
    titleNameArray = @[NSLocalizedString(@"telePhone", nil),NSLocalizedString(@"email", nil),NSLocalizedString(@"roleId", nil),NSLocalizedString(@"openRoomPower", nil),NSLocalizedString(@"setOpenTime", nil),NSLocalizedString(@"managerPower", nil)];
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    roleArray = @[NSLocalizedString(@"manager", nil),NSLocalizedString(@"subManagement", nil),NSLocalizedString(@"general", nil)];
    [self prepareBtnView];
    [self prepareTableView];
    [self prepareFirstSectionView];
    [self prepareBackView];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    moreViewBtn.hidden = NO;
    backBtn.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    moreViewBtn.hidden = YES;
    backBtn.hidden = YES;
}

-(void)prepareTableView
{
    float x = 0;
    float y = 0;
    float height = UI_SCREEN_HEIGHT - 64 - y;
    float width = UI_SCREEN_WIDTH;
    
    staffInfoTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStyleGrouped];
    staffInfoTabelView.backgroundColor = UIColorFromRGB(0xebebeb);
    staffInfoTabelView.delegate = self;
    staffInfoTabelView.dataSource = self;
    staffInfoTabelView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:staffInfoTabelView];
}

-(void)prepareFirstSectionView
{
    float x = 0;
    float y = 0;
    float height = 78;
    float width = UI_SCREEN_WIDTH;
    firstSectionView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    
    x = 22;
    y = (78 - 48) / 2.0;
    height = 48;
    width = 48;
    UIImageView * headerImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [headerImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HEADERURL,_model.headUrl]] placeholderImage:[UIImage imageNamed:@"ic_加载头像212"]];
    headerImageView.layer.cornerRadius = 24;
    headerImageView.layer.masksToBounds = YES;
    [firstSectionView addSubview:headerImageView];
    
    x = 94;
    width = UI_SCREEN_WIDTH - x - 40;
    height = 20;
    y = (78 - 20)/2.0;
    nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    nameLabel.font = [UIFont systemFontOfSize:16.0];
    nameLabel.textColor = UIColorFromRGB(0x333333);
    nameLabel.text = _model.userName;
    [firstSectionView addSubview:nameLabel];
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16],};
    CGSize textSize = [_model.userName boundingRectWithSize:CGSizeMake(500, 20) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
    x += textSize.width + 10;
    y = (78 - 14)/2.0;
    height = 14;
    width = 12;
    sexImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    if ([_model.sex isEqualToString:@"1"]) {
       sexImageView.image = [UIImage imageNamed:@"male"];
    }
    else if ([_model.sex isEqualToString:@"0"])
    {
        sexImageView.image = [UIImage imageNamed:@"female"];
    }
    [firstSectionView addSubview:sexImageView];
    
}

#pragma mark ----------- 导航栏上的btn
-(void)prepareBtnView
{
    float x = UI_SCREEN_WIDTH - 40;
    float y = 0;
    float width = 40;
    float height = 40;
    moreViewBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    moreViewBtn.frame = CGRectMake(x, y, width, height);
    [moreViewBtn addTarget:self action:@selector(showOrHiddenMoreView) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:moreViewBtn];
    
    x = 20;
    width = 4;
    height = 18;
    y = 11;
    UIImageView * moreImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    moreImageView.image = [UIImage imageNamed:@"moreInfo"];
    [moreViewBtn addSubview:moreImageView];
    
    x = 0;
    y = 0;
    width = 56;
    height = 40;
//    UIButton * btn = [BackBtn initWithFrame:CGRectMake(x, y, width, height) withImage:@"navigationBack"];
    backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(x, y, width, height);
    [self.navigationController.navigationBar addSubview:backBtn];
    [backBtn addTarget:self action:@selector(userInfoBack) forControlEvents:UIControlEventTouchUpInside];
}

-(void)showOrHiddenMoreView
{
    backView.hidden = !backView.hidden;
}

#pragma mark ------- 准备右上角的更多view
-(void)prepareBackView
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT;
    backView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
    backView.userInteractionEnabled = YES;
    backView.hidden = YES;
    [self.view addSubview:backView];
    UITapGestureRecognizer * tapAllBackView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenView)];
    tapAllBackView.delegate = self;
    [backView addGestureRecognizer:tapAllBackView];
    
    x = backView.frame.size.width - 22;
    y = 4;
    width = 11;
    height = 6;
    UIImageView * triangleView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    triangleView.image = [UIImage imageNamed:@"triangle"];
    triangleView.backgroundColor = [UIColor clearColor];
    [backView addSubview:triangleView];
    
    x = UI_SCREEN_WIDTH - 134;
    y = 10;
    width = 128;
    height = 39 * 2;
    if ([[InternationalControl userLanguage]isEqualToString:@"en"]) {
        x = UI_SCREEN_WIDTH / 2.0 - 26;
        width = UI_SCREEN_WIDTH / 2.0 + 20;
    }
    backListView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    backListView.backgroundColor = [UIColor blackColor];
    backListView.layer.cornerRadius = 2;
    [backView addSubview:backListView];
    
    x = 0;
    y = 0;
    height = 39;
    DeleteView * firstView = [[DeleteView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    firstView.imageString = @"edit";
    firstView.titleString = NSLocalizedString(@"modifyStaffInfo", nil);
    UITapGestureRecognizer * firstTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(editTap)];
    firstTap.delegate = self;
    [firstView addGestureRecognizer:firstTap];
    [backListView addSubview:firstView];
    
    x = 16;
    y = 39;
    width -= 2 * x;
    height = 0.5;
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    lineView.backgroundColor = RGBA(81, 81, 81, 1);
    [backListView addSubview:lineView];
    
    x = 0;
    y = 39.5;
    width = firstView.frame.size.width;
    height = 39;
    DeleteView * secondeView = [[DeleteView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    secondeView.imageString = @"delete";
    secondeView.titleString = NSLocalizedString(@"delete", nil);
    UITapGestureRecognizer * secondeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(deleteTap)];
    secondeTap.delegate = self;
    [secondeView addGestureRecognizer:secondeTap];
    [backListView addSubview:secondeView];
}

-(void)hiddenView
{
    backView.hidden = YES;
}

#pragma mark --------- 编辑操作
-(void)editTap
{
    if (![self canDoByRole]) {
        [PromptInfoView showMessage:NSLocalizedString(@"noPowerEdit", nil)];
        return;
    }
    [self hiddenView];
    EidtStaffInfoController * esfc = [[EidtStaffInfoController alloc]initWithModel:_model];
    esfc.editStaffBlock = ^(StaffModel * model)
    {
        nameLabel.text = model.userName;
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16],};
        CGSize textSize = [_model.userName boundingRectWithSize:CGSizeMake(500, 20) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
        sexImageView.frame = CGRectMake(nameLabel.frame.origin.x + textSize.width + 10 , sexImageView.frame.origin.y, sexImageView.frame.size.width, sexImageView.frame.size.height);
    };
    [self.navigationController pushViewController:esfc animated:YES];
}

#pragma mark --------- 删除操作
-(void)deleteTap
{
    if (![self canDoByRole]) {
        if (_role == 3) {
            [PromptInfoView showMessage:NSLocalizedString(@"noPowerDelete", nil)];
        }
        else if ([_model.StaffRole integerValue] == 1)
        {
            [PromptInfoView showMessage:NSLocalizedString(@"cannotDeleteManager", nil)];
        }
        else if (_role == 2)
        {
            [PromptInfoView showMessage:NSLocalizedString(@"cannotDelete", nil)];
        }
        else
        {
            [PromptInfoView showMessage:NSLocalizedString(@"noPowerDelete", nil)];
        }
        return;
    }
    [self hiddenView];
    UIActionSheet * quitAcitonSheet = [[UIActionSheet alloc]initWithTitle:NSLocalizedString(@"deleteOrNot", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"not", nil) destructiveButtonTitle:NSLocalizedString(@"yes", nil) otherButtonTitles:nil];
    [quitAcitonSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self deleteCell];
    }
}

#pragma mark ----------- 根据权限来判断是否可以删除和修改
-(BOOL)canDoByRole
{
    if (rolePower == 0) {
        return NO;
    }
    else
        return YES;
}

#pragma mark --- 删除cell

-(void)deleteCell
{
    if ([self IsHaveNetwork])
    {
        return;
    }
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    [postDict setValue:_model.userID forKey:@"memberIds"];
    if([self getTimestamp:[QRSingleton sharedQRSingleton].communityId timeKey:@"member_timestamp"] != nil)
    {
        [postDict setValue:[self getTimestamp:[QRSingleton sharedQRSingleton].communityId timeKey:@"member_timestamp"] forKey:@"timestamp"];
    }
    else
    {
        [postDict setValue:@"" forKey:@"timestamp"];
    }
    [self startWaiting:nil color:nil addToView:self.view];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    __block StaffManagerViewController * weakSelf = self;
    [rnk initWithPath:POST(DELETEUSER) params:postDict block:^(id downLoadData, id error) {
        [weakSelf stopWaiting];
        NSDictionary * cache = [downLoadData objectForKey:@"cache"];
        NSDictionary * data = [downLoadData objectForKey:@"data"];
        if(cache != nil)
        {
            if([@"1" isEqualToString:[NSString stringWithFormat:@"%@",[cache objectForKey:@"status"]]]==YES)
            {
//                [weakSelf lookCommunityRole];
            }
            else
            {
                [weakSelf updateTimestamp:[QRSingleton sharedQRSingleton].communityId timeKey:@"member_timestamp" timeKeyValue:[cache objectForKey:@"timestamp"]];
                if(data != nil)
                {
                   StaffLogic * staffDataBase = [[StaffLogic alloc]init];
                   [staffDataBase deleteStaffData:_model.userID communityId:[QRSingleton sharedQRSingleton].communityId];
                    
                }
            }
            [self userInfoBack];
        }
        else
        {
            if([[error objectForKey:@"status"]integerValue] == 331)
            {
                StaffLogic * staffDataBase = [[StaffLogic alloc]init];
                [staffDataBase deleteStaffData:_model.userID communityId:[QRSingleton sharedQRSingleton].communityId];
                [self userInfoBack];
            }
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
    }];
    
}


#pragma mark --------- tableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger count = 5;
    switch (rolePower) {
        case 0:
            count = 3;
            break;
        case 1:
            count = 5;
            break;
        case 2:
            count = 4;
            break;
        default:
            count = 5;
            break;
    }
    return count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 2 || section == 4) {
        return 1;
    }
    else
    {
        return 2;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 78.0;
    }
    else
        return 56;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 16.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * identityId = @"cell";
    StaffInfoCell * cell = [tableView dequeueReusableCellWithIdentifier:identityId];
    if (!cell) {
        cell = [[StaffInfoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identityId];
    }
    if (indexPath.section == 0) {
        [cell addSubview:firstSectionView];
    }
    else
    {
        if (indexPath.section == 1)
        {
            cell.titleNameString = titleNameArray[indexPath.row];
            if (indexPath.row == 0) {
                cell.contentString = _model.mobile;
                cell.contentColor = UIColorFromRGB(0x00aff0);
            }
            else
            {
                cell.contentString = _model.email;
                cell.contentColor = UIColorFromRGB(0x333333);
            }
        }
       else if (indexPath.section == 2)
        {
            cell.titleNameString = titleNameArray[indexPath.section + indexPath.row];
            cell.contentString = roleArray[[_model.StaffRole integerValue] - 1];
            cell.contentColor = UIColorFromRGB(0x727272);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        else
        {
            if (indexPath.section == 3) {
                cell.titleNameString = titleNameArray[indexPath.section + indexPath.row];
            }
            else if (indexPath.section == 4)
            {
                cell.titleNameString = titleNameArray[5];
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1)
    {
        if (indexPath.row == 0) {
            if(!(_model.mobile==nil || [_model.mobile isEqualToString:@""])){
                [self callPhone];
            }
//            [self callPhone];
        }
    }
    else if (indexPath.section == 2)
    {
        EditStaffRoleController * esrc = [[EditStaffRoleController alloc]initWithModel:_model];
        [self.navigationController pushViewController:esrc animated:YES];
        esrc.editStaffBlock = ^(StaffModel * newModel)
        {
            _model = newModel;
            [staffInfoTabelView reloadData];
        };
    }
    else if (indexPath.section == 3)
    {
        if (indexPath.row == 0) {
            RoomSeclectViewController * rsvc = [[RoomSeclectViewController alloc]init];
            rsvc.communityid = _communityId;
            rsvc.memberid = _model.userID;
            rsvc.guestOrStaff = @"1";
            [self.navigationController pushViewController:rsvc animated:YES];
        }
        else
        {
            StaffTimeSelectViewController * stvc = [[StaffTimeSelectViewController alloc]init];
            stvc.communityId = _communityId;
            stvc.staffUid = _model.userID;
            [self.navigationController pushViewController:stvc animated:YES];
        }
    }
    else if (indexPath.section == 4)
    {
        AccessSeclectViewController * asvc = [[AccessSeclectViewController alloc]init];
        asvc.communityid = _communityId;
        asvc.memberid = _model.userID;
        [self.navigationController pushViewController:asvc animated:YES];
    }
}

#pragma mark ---------- 系统打电话
-(void)callPhone
{
    NSString * callString = nil;
    if (![_model.areaCode isEqualToString:[QRSingleton sharedQRSingleton].currentAreaCodeString]) {
        callString = [NSString stringWithFormat:@"+%@-%@",_model.areaCode,_model.mobile];
    }
    else
    {
        callString = _model.mobile;
    }
    NSString *telUrl = [NSString stringWithFormat:@"telprompt://%@",callString];
    NSURL *url = [NSURL URLWithString:telUrl];
    [[UIApplication sharedApplication] openURL:url];
}

-(void)userInfoBack
{
   [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
}

-(void)setModel:(StaffModel *)model
{
    _model = model;
    rolePower = [JudgeRole judgeRoleShowStaffInfo:[_model.StaffRole integerValue] withRole:_role];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
